<?php


namespace App\Exports;

use App\Models\RecordBalance;
use App\Models\RecordRecharge;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
/**
 * Created By FreeAbrams
 * Date: 2020/11/27
 */
class MemberExport implements FromView
{
	protected $timeBetween;
	
	public function __construct($timeBetween)
	{
		$this->timeBetween = $timeBetween;
	}
	
	public function view():View
	{
		$temp = $this->data($this->timeBetween);

		return view('admin.export.member-export-table', $temp);
	}
	
	public function data($timeBetween)
	{
		$recordRecharge = RecordRecharge::whereBetween('created_at', $timeBetween)
			->get(['id', 'type', 'price', 'created_at']);
		
		$recordRechargeGroup = $recordRecharge->groupBy('type');
		
		// 会员卡充值
		$recharge = $recordRecharge->whereIn('type', [1, 2]);
		// 充值赠送
		$giving = $recordRecharge->where('type', 3);
		// 余额消费
		$balance = RecordBalance::whereBetween('created_at', $timeBetween)
			->where('type', '<>', '1')
			->get(['id','type', 'price', 'created_at']);
		
		// groupBy date
		$recharge = $recharge->map(function ($item) {
			$time = new Carbon($item->created_at);
			$item->date = (int)$time->format('m');
			return $item;
		})->groupBy('date');
		$giving = $giving->map(function ($item) {
			$time = new Carbon($item->created_at);
			$item->date = (int)$time->format('m');
			return $item;
		})->groupBy('date');
		$balance = $balance->map(function ($item) {
			$time = new Carbon($item->created_at);
			$item->date = (int)$time->format('m');
			return $item;
		})->groupBy('date');
		
		$temp['sumRecharge'] = 0;
		$temp['sumGiving'] = 0;
		$temp['sumBalance'] = 0;
		
		$res = [
			'recharge' => $recharge,
			'giving' => $giving,
			'balance' => $balance,
			'sumRecharge' => $this->sumPrice($recharge),
			'sumGiving' => $this->sumPrice($giving),
			'sumBalance' => $this->sumPrice($balance),
		];

		return $res;
	}
	
	public function sumPrice($collection)
	{
		$price = 0;
		
		foreach ($collection as $v)
		{
			$price += $v->sum('price');
		}
		
		return $price;
	}
}